/**
 * 扩展一个test模块
 */

layui.define(function(exports) { // 提示：模块也可以依赖其它模块，如：layui.define('layer',
	var obj = {
		BASE_URL : "http://localhost:8088",
		UPLOAD_URL : "http://localhost:8088/common/upload/file",
		PAGE_SIZE : 10,
		PAGE_NUM : 0,
		DEL_URL : "",  //删除请求地址
		SAVE_URL:"",//新增后台地址
		EDIT_URL:"",//编辑后台地址
		DETAIL_URL:"",//详情后台地址
		PAGE_URL:"",
		TITLE:"",
		AREA : [ '800px', '450px' ],
		SHADE : [ 0.8, '#393D49' ],
		EDIT_HTML:"edit.html",
		page:0,
		pageSize:10,
		gird_col:null, 
		gird_where:null, 
		gird_url:null, 
		gird_el:null, 
		gird_event:null,
		getUrlParam : function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
			var r = window.location.search.substr(1).match(reg); // 匹配目标参数
			if (r != null)
				return unescape(r[2]);
			return null; // 返回参数值
		},
		getUrlAllParams : function() {
			var query = window.location.search.substring(1);
			var vars = query.split("&");
			var params = {};
			for (var i = 0; i < vars.length; i++) {
				var pair = vars[i].split("=");
				var key = pair[0];
				if (key != "" && key != null && key != undefined) {
					var val = pair[1];
					params[key] = val;
				}

			}
			var isNull = JSON.stringify(params) == "{}";
			if (isNull == true) {
				return null;
			}
			return params;
		},
		init : function(params) {
			var url = params.url;
			var title = params.title;
			this.DEL_URL = url+"/del";
			this.SAVE_URL = url+"/save";
			this.EDIT_URL= url+"/edit";
			this.DETAIL_URL= url+"/detail";
			this.PAGE_URL = url+"/page";
			this.TITLE = title;
			if (params.area != null && params.area != "" && params.area != undefined) {
				this.AREA = params.area;
			}
			if (params.shade != null && params.shade != "" && params.shade != undefined) {
				this.SHADE = params.shade;
			}
		},
		del : function(obj) {
			var loadding = layer.msg('操作中', {
				icon : 16,
				shade : 0.01
			});
			layui.use([ "global", "jquery" ], function() {
				var global = layui.global;
				var BASE_URL = layui.global.BASE_URL;
				$.post(BASE_URL + global.DEL_URL, {
					id : obj
				}, function(data) {
					layer.close(loadding);
					if (data.code == 200) {
						layer.msg('操作成功', {
							icon : 1,
							time : 2000
						}, function() {
							global.grid(col, null, el);
						});
					}
					if (data.code != 200) {
						layer.msg(data.msg, {
							icon : 2,
							time : 1000
						});
					}
				})
			});
		},
		DEFAULT_EVENT : function(obj) {
			var data = obj.data;
			layui.use([ "global","jquery","form"], function() {
			if (obj.event === 'del') {
				layer.confirm('确认删除吗?', function(index) {
					layer.close(index);
					layui.use([ "global", "upload" ], function() {
						var global = layui.global;
						global.del([ data.id ]);
					})
				});
			}
			if (obj.event === 'edit') {
				global.edit(obj.data.id);
			}
			if (obj.event === 'detail') {
				detail(obj.data.id);
			}
			})
		},
		initForm : function(url, name) {
			layui.use([ "global","jquery","form"], function() {
				var global = layui.global;
				var form = layui.form;
				var params = global.getUrlAllParams();
				var BASE_URL = global.BASE_URL;
				if (params != null && params != "" && (typeof(params) != "undefined")) {
					$.post(BASE_URL+url,params,function(data){
						  form.val(name, data.data);
					})
				}
			});
		},
		grid : function(col, where, el, event) {
			layui.use([ "global", 'table' ], function() {
				var global = layui.global;
				global.gird_col = col;
				global.gird_url = url; 
				global.gird_where = where;
				global.gird_el = el;
				global.gird_event = event;
				if (where == null || where == undefined || where == "") {
					where = {
						pageNum : global.PAGE_NUM,
						pageSize : global.PAGE_SIZE
					};
				}
				if (where.pageNum == null || where.pageNum == undefined || where.pageNum == "") {
					where["pageNum"] = global.PAGE_NUM;
				}
				if (where.pageSize == null || where.pageSize == undefined || where.pageSize == "") {
					where["pageSize"] = global.PAGE_SIZE;
				}
				$.post(global.BASE_URL + global.PAGE_URL, where, function(data) {
					var total = data.data.total;
					var table = layui.table;
					var laypage = layui.laypage;
					form = layui.form;
					var loadding = layer.msg('加载中', {
						icon : 16,
						shade : 0.01
					});
					// 第一个实例
					table.render({
						elem : "#" + el,
						height : 'full', // 高度最大化减去差值
						data : data.data.list,
						toolbar : "#toolbar",
						limit : where.pageSize,
						loading : true,
						defaultToolbar : [ 'filter' ],
						skin : 'line',
						even : true, // 开启隔行背景
						cols : col,
						done : function(res, curr, count) {
							layer.close(loadding);
							laypage.render({
								elem : 'page',
								limits : [ 10, 20, 100 ],
								limit : where.pageSize,
								group : 2,
								curr : where.pageNum,
								prev : "<",
								next : ">",
								layout : [ 'prev', 'page', 'next', 'skip',
										'count', "limit" ],
								count : total,
								jump : function(obj, first) {
									if (!first) {
										var limit = obj.limit;
										var curr = obj.curr;
										where["pageSize"] = limit;
										where["pageNum"] = curr;
										layui.use([ "global" ], function() {
											var global = layui.global;
											global.page = curr;
											global.pageSize = limit;
											global.gird_where = where;
											global.grid(col, where, el);
										})
									}
								}
							});
						}
					});
					// 头工具栏事件
					table.on('toolbar(' + el + ')', function(obj) {
						var check = table.checkStatus(obj.config.id);
						layui.use([ "global", "layer" ], function() {
							var global = layui.global;
							switch (obj.event) {
							case 'add':
								global.edit();
								break;
							case 'update':
								if (check.data.length > 1 || check.data.length == 0) {
									layer.msg("请选择一条后再操作");
									return;
								}
								global.edit(check.data[0].id);
								break;
							case 'status':
								if (check.data.length > 1 || check.data.length == 0) {
									layer.msg("请选择一条后再操作");
									return;
								}
								break;
							case 'delete':
								var id = [];
								$(check.data).each(function(index, item) {
									id.push(item.id);
								})
								if (id.length == 0) {
									layer.msg("请选择一条后再操作");
									return;
								}
								layer.confirm('确认删除吗?', function(index) {
									layer.close(index);
									global.del(id);
								});
								break;
							}
						});
					});

					if (event == null || event == undefined || envent == "") {
						event = global.DEFAULT_EVENT;
					}
					// 监听行工具事件
					table.on('tool(' + el + ')', event);
				})
			})
		},
		gridReload:function(where){
			layui.use([ "global"], function() {
				var global = layui.global;
				var _where = global.gird_where;
				if(where != null && where != undefined  && where != ""){
					_where = where;
				}
				global.grid(global.gird_col, _where, global.gird_el, global.gird_event);
			})
		},
		search:function(){
			layui.use(["global", "form","jquery" ], function() {
				var form = layui.form;
				var global = layui.global;
				// 监听提交
				form.on("submit(search)", function(data) {
					global.gridReload(data.field);
					return false;
				});
			});
		},
		submit:function(url,sucess,error){
			layui.use([ "global", "form","jquery"], function() {
				var global = layui.global;
				var form = layui.form;
				// 监听提交
				form.on("submit(submit)", function(data) {
					var params = global.getUrlAllParams();
					var url = "";
					if(params != null && params !="" && params !=undefined){
						url = global.EDIT_URL;
					}else{
						url = global.SAVE_URL;
					}
					debugger;
					global.update(url,data.field,sucess,error);
					return false;
				});
			});
		},
		edit:function(id) {
			layui.use([ "global"], function() {
				var global = layui.global;
				var title = "新增"+global.TITLE;
				if (id != "" && id != null && id != undefined) {
					title = "编辑"+global.TITLE;
				}
				var url = global.EDIT_HTML;
				if (id != "" && id != null && id != undefined) {
					url += "?id=" + id;
				}
				global.dialog(title, url);
			})
		},
		dialog:function (title, url) {
			layui.use([ "global"], function() {
				var global = layui.global;
				layui.layer.open({
					title : title,
					type : 2,
					area : global.AREA,
					shade : global.SHADE,
					content : url,
					success : function(layero, index) {
						setTimeout(function() {
							layui.layer.tips('点击此处返回'+global.TITLE+'列表','.layui-layer-setwin .layui-layer-close', {tips : 3});
						}, 500)
					}
				})
			})
			
		},
		update:function(url,params,sucess,error){
			layui.use([ "global", "form","jquery"], function() {
				var global = layui.global;
				$.post(global.BASE_URL + url, params, function(data) {
					if (data.code == 200) {
						if (sucess != null && sucess != "" && sucess != undefined) {
							sucess(data);
							return;
						}
						var index = parent.layer.getFrameIndex(window.name);
						layer.msg('操作成功', {
							icon : 1,
							time : 2000
						}, function() {
							parent.layer.close(index);
							var _parent = window.parent;
							try {
								window.parent.global.gridReload();
							} catch (e) {
								global.gridReload();
							}
						});
					}
					if (data.code != 200) {
						if (error != null && error != "" && error != undefined) {
							error(data);
							return;
						}
						layer.msg(data.msg, {
							icon : 2,
							time : 1000
						});
					}

				})
			});
		},
		upload:function(success) {
			layui.use([ "global", "upload" ], function() {
			
				var upload = layui.upload;
				var url = layui.global.UPLOAD_URL;
				// 拖拽上传
				var loadding;
				upload.render({
					elem : '#upload',
					acceptMime : 'image/jpg, image/png',
					url : url,
					before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
						loadding = layer.msg('上传中', {
							icon : 16,
							shade : 0.01
						});
					  },
					done : function(res, index, upload) {
						layer.close(loadding);
						success(res);
					}
				});
			});
		},
		status:function(){
			layui.use([ "form","global" ], function() {
				var form = layui.form;
				var global = layui.global;
				 //监听性别操作
				  form.on('switch(statusFilter)', function(obj){
					  var id = obj.elem.id;
					  var check =obj.elem.checked;
					  var val = check == true?0:1;
					  global.update(global.EDIT_URL,{id:id,status:val});
				  });
				  //监听锁定操作
				  form.on('checkbox(statusFilter)', function(obj){
					  var id = obj.elem.id;
					  var check =obj.elem.checked;
					  var val = check == true?0:1;
					  global.update(global.EDIT_URL,{id:id,status:val});
				  });
			})
		},
	};
	
	obj.search();
	obj.status();
	$("body").append("<div id='_template_global'></div>");
    $('#_template_global').load('../../template/template.html');
	// 输出test接口
	exports('global', obj);
});